﻿<template>
  <info-card title="方案设置" ref="cardRef">
    <!-- 指定方案 -->
    <el-tabs v-model="currentPlan" v-if="showPlanTab && planData.length > 0">
      <el-tab-pane v-for="(item, index) in planData" :key="item.id" :label="item.planName" :name="index">
        <InfoPlanItem
          :attribute-list="attributeList"
          :operable-attr-list="operableAttrList"
          :area-data="areaData"
          :ref="el => setPlanItemRef(el, index)"
        />
      </el-tab-pane>
    </el-tabs>
    <!-- 统一方案 -->
    <InfoPlanItem
      :attribute-list="attributeList"
      :operable-attr-list="operableAttrList"
      :area-data="areaData"
      ref="unifiedPlanRef"
      v-else
    />
  </info-card>
</template>

<script setup>
  import infoCard from "./InfoCard.vue";
  import InfoPlanItem from "./InfoPlanItem.vue";
  import mittBus from "tools-utils/mitt";
  const props = defineProps({
    productDetail: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  // 卡片Ref
  const cardRef = ref();
  // 当前方案
  const currentPlan = ref(0);
  // 属性列表（原数据）
  const attributeList = ref([]);
  // 已选择的父级
  const checkParenAttr = ref([]);
  // 地区数据
  const areaData = ref([]);
  // 表格加载
  const loading = ref(false);
  // 当前所有方案
  const planData = ref([]);
  // 是否显示多方案tab
  const showPlanTab = ref(false);
  // 统一方案Ref
  const unifiedPlanRef = ref();
  // 方案ref列表
  const planRefList = ref([]);
  // 所有方案数据
  const allPlanData = ref([]);
  // 可操作属性
  const operableAttrList = ref([]);
  // 暂存的所有方案数据
  const stagingPlanData = ref([]);
  // 详情
  const detail = inject("detail");
  // 监听详情属性变化
  watch(detail, val => {
    init();
  });
  // 设置子元素ref
  const setPlanItemRef = (el, index) => {
    if (el) {
      planRefList.value[index] = el;
    }
  };
  // 初始化
  onMounted(() => {
    mittBus.on("showMutiple", handleShowMutiple);
    mittBus.on("updatePlan", handleUpdatePlan);
    loadAttributeData();
    loadAreaList();
  });
  onUnmounted(() => {
    mittBus.off("showMutiple", handleShowMutiple);
    mittBus.off("updatePlan", handleUpdatePlan);
  });
  // 详情初始化
  const init = () => {
    if (detail.value.rentPlan === 2) {
      showPlanTab.value = true;
      planData.value = detail.value.productRentPlanList.map((item, index) => {
        return { ...item, planChannelList: item.productChannelList.map(el => el.channelId) };
      });
      nextTick(() => {
        planData.value.forEach((item, index) => {
          planRefList.value[index]?.init(item);
        });
      });
    } else {
      unifiedPlanRef.value.init();
    }
  };
  // 重置方案数据
  const planDataReset = () => {
    // planSettingRef?.value?.resetFields();
    // planSettingForm.value = {
    //   rentModelTypeList: [],
    //   returnRule: "",
    //   buyOutRule: "",
    //   buyRule: "",
    //   periodType: [],
    //   periodDays: "",
    //   chooseSpecList: [],
    //   productSkuList: [],
    //   deliveryPostage: "",
    //   areaList: [],
    //   returnPostage: "",
    //   returnAddressIdList: [],
    // };
    // searchParams.value = {
    //   pageNumber: 1,
    //   pageSize: 10,
    //   type: 2,
    // };
    // checkParenAttr.value = [];
  };
  // 打开多方案
  const handleShowMutiple = show => {
    showPlanTab.value = show;
  };
  // 更新方案
  const handleUpdatePlan = updateParams => {
    if (!showPlanTab.value) {
      showPlanTab.value = true;
    }
    // 方案删除
    if (updateParams.type === "del") {
      planData.value.splice(updateParams.delIdx, 1);
      // planRefList.value.splice(updateParams.delIdx, 1);
    } else {
      // 添加方案
      planData.value.push(updateParams.newPlan);
    }
  };
  // 获取属性
  const loadAttributeData = () => {
    Api.product.getAttributeList().then(res => {
      attributeList.value = JSON.parse(JSON.stringify(res.data));
      operableAttrList.value = res.data.filter(el => el.subsets.length > 0);
    });
  };
  // 获取地区数据
  const loadAreaList = () => {
    loading.value = true;
    Api.common.getAreaData().then(res => {
      loading.value = false;
      areaData.value = res.data;
    });
  };

  // 单个方案表单验证
  const formVerifySingle = () => {
    return unifiedPlanRef.value.formVerify();
  };
  // 多个方案验证
  const formVerifyMutiple = async () => {
    // 校验失败表单名称
    const errorPlanNameGroup = [];
    // 校验成功数据
    const successList = [];
    for (let i = 0; i < planRefList.value.length; i++) {
      const res = await planRefList.value[i].formVerify();
      if (!res) {
        errorPlanNameGroup.push(planData.value[i].planName);
      } else {
        const productSpecAssociation = {
          chooseSpecList: planRefList.value[i].checkParenAttr,
          allSpecList: planRefList.value[i].optionalAttrList.map(el => el.id),
          productAttributeList: planRefList.value[i].optionalAttrList.map(el => {
            return { id: el.id, childrenIdList: el.subsets.map(el => el.id) };
          }),
        };
        // 方案设置
        const planParams = planRefList.value[i].planSettingForm;
        // 物流信息
        const logisticalParams = planRefList.value[i].getLogistiParams();
        const productSkuList = planRefList.value[i].planSettingForm.productSkuList.map(item => {
          const productSkuPriceList = [];
          for (let key in item.rentDay) {
            if (!item.rentDay[key].disabled) {
              const priceItem = {
                shortChoose: 0,
                days: key,
                dayPrice: item.rentDay[key].dayPrice,
                underlinePrice: item.rentDay[key].underlinePrice,
                salePrice: item.rentDay[key].salePrice,
              };
              productSkuPriceList.push(priceItem);
            }
          }
          return {
            imageUrl: item?.imageUrl[0],
            hideFlag: item.hideFlag,
            officialPrice: item.officialPrice,
            purchasePrice: item.purchasePrice,
            quantity: item.quantity,
            productSkuSpecList: item.allSkus.map(el => el.id),
            productRentModelTypeList: [{ rentModelType: item.rentModelType, productSkuPriceList }],
          };
        });
        const planItem = {
          ...planParams,
          ...logisticalParams,
          productSpecAssociation,
          productSkuList,
          planName: planData.value[i].planName,
          planChannelList: planData.value[i].planChannelList,
        };
        delete planItem.chooseSpecList;
        delete planItem.areaList;
        successList.push(planItem);
      }
    }

    if (errorPlanNameGroup.length === 0) {
      allPlanData.value = [...successList];
      return true;
    } else {
      $msg.error(`${errorPlanNameGroup.join("、")}必填项未填写`);
      return false;
    }
  };
  const getTop = () => {
    return cardRef.value.getTop();
  };
  // 暴露方法
  defineExpose({
    formVerifySingle,
    formVerifyMutiple,
    getTop,
    checkParenAttr,
    planData,
    currentPlan,
    planRefList,
    allPlanData,
    unifiedPlanRef,
  });
</script>

<style lang="scss" scoped>
  .check-item {
    width: 600px;
  }
  .check-item-bottom {
    width: 100%;
    // height: 185px;
    margin-top: 8px;
    display: flex;
    .bottom-item {
      width: 620px;
      margin-right: 30px;

      .bottom-item-content {
        width: 100%;
        border-radius: 8px;
        border: 1px solid var(--cb1);
        padding: 16px;
        display: flex;
      }
      .bottom-flex {
        justify-content: space-around;
      }
    }
  }
  .attr-list {
    min-width: 550px;
    padding: 16px;
    border: 1px solid var(--cb1);
    border-radius: 8px;
    .attr-list-title {
      width: 100%;
      color: var(--ct1);
      font-size: 14px;
      font-weight: bold;
    }
    .attr-children {
      color: var(--ct1);
      font-size: 14px;
    }
    .attr-parent {
      width: 100%;
      color: var(--ct1);
      font-size: 14px;
      .attr-parent-item {
        height: 30px;
        padding: 0 12px;
        font-size: 14px;
        color: var(--ct2);
        background-color: var(--fl1);
        cursor: pointer;
        border-radius: 4px;
      }
      .attr-parent-item-active {
        color: var(--bd);
        background-color: var(--bd9);
      }
    }
  }
  .reset-btn {
    position: absolute;
    right: 0;
    top: 0;
  }
  .sku-img {
    width: 100%;
    display: flex;
    justify-content: center;
    flex-wrap: wrap;
    .sku-img-text {
      width: 100%;
      text-align: center;
      font-size: 14px;
      color: var(--ct2);
      margin-top: 4px;
    }
  }
  .logistical-title {
    width: 100%;
    color: var(--ct1);
    font-size: 16px;
    margin-bottom: 16px;
    font-weight: bold;
  }
</style>
